package com.migu.contacts.main.todo;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.migu.contacts.net.Service.API;

import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.frank.libandroid.BaseActivity;
import com.frank.libandroid.BaseAdapter;
import com.frank.libandroid.BottomPopup;
import com.frank.libandroid.DataStore;
import com.frank.libandroid.HttpCallback;
import com.frank.libandroid.butterknife.BindAdapter;
import com.frank.libandroid.butterknife.OnClick;
import com.lxj.xpopup.XPopup;
import com.migu.contacts.R;
import com.migu.contacts.bean.ActionBean;
import com.migu.contacts.bean.ContactBean;
import com.migu.contacts.bean.DetailBean;
import com.migu.contacts.bean.EventBean;
import com.migu.contacts.bean.GroupBean;
import com.migu.contacts.databinding.ActivityCreateTodoBinding;
import com.migu.contacts.databinding.ItemContactEditContactBinding;
import com.migu.contacts.databinding.ItemCreateTodoBinding;
import com.migu.contacts.databinding.ItemCreateTodoCycleBinding;
import com.migu.contacts.databinding.ItemCreateTodoImportanceBinding;
import com.migu.contacts.databinding.ItemCreateTodoNoticeBinding;
import com.migu.contacts.databinding.ItemSelectGroupDetailBinding;
import com.migu.contacts.databinding.PopTodoCycleBinding;
import com.migu.contacts.databinding.PopTodoImportanceBinding;
import com.migu.contacts.databinding.PopTodoNoticeBinding;
import com.migu.contacts.net.ResultCallback;
import com.migu.contacts.util.AvatarUtil;
import com.migu.contacts.util.CycleUtil;
import com.migu.contacts.util.NoticeUtil;
import com.migu.contacts.util.PopUtil;
import com.migu.contacts.widget.Callback;
import com.migu.contacts.widget.Label2;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

public class CreateTodoActivity extends BaseActivity<ActivityCreateTodoBinding> {
    @BindAdapter(R.id.recyclerView1)
    BaseAdapter<ItemCreateTodoBinding, Label2.LabelBean> topAdapter = new BaseAdapter<ItemCreateTodoBinding, Label2.LabelBean>() {
        @OnClick(R.id.iv_arrow)
        public void iv_arrow(Label2.LabelBean bean, int position) {
            if (mBinding.toggle.isChecked()) {
                String str = bean.right;
                if (str != null && str.contains(" ")) {
                    str = str.split(" ")[0];
                }
                PopUtil.showDatePicker(mActivity, str, new Callback<String>() {
                    @Override
                    public void onComplete(String s) {
                        bean.right = s;
                        bean.notifyChange();
                        if (position == 0) {
                            actionBean.startTime = bean.right;
                        } else {
                            actionBean.endTime = bean.right;
                        }
                    }
                });
            } else {
                String str = bean.right;
                if (str != null && !str.contains(" ")) {
                    str = str + " 09:00";
                }
                PopUtil.showDateTimePicker(mActivity, str, new Callback<String>() {
                    @Override
                    public void onComplete(String s) {
                        bean.right = s;
                        bean.notifyChange();
                        if (position == 0) {
                            actionBean.startTime = s;
                        } else {
                            actionBean.endTime = s;
                        }
                    }
                });
            }

        }
    };
    @BindAdapter(R.id.recyclerView2)
    BaseAdapter<ItemCreateTodoBinding, Label2.LabelBean> midAdapter = new BaseAdapter<ItemCreateTodoBinding, Label2.LabelBean>() {
        @OnClick(R.id.iv_arrow)
        public void iv_arrow(Label2.LabelBean bean, int position) {
            if (position == 0) {
                showPopNotice(bean);
            } else if (position == 1) {
                showCyclePop(bean);
            } else if (position == 2) {
                showImportancePop(bean);
            }
        }
    };

    private void showImportancePop(Label2.LabelBean bean) {
        BottomPopup bottomPopup = new BottomPopup<PopTodoImportanceBinding>(mActivity) {

            ImportanceBean checkedNotice = actionBean.momentsMatter == 0 ? null : new ImportanceBean(actionBean.momentsMatter);
            @BindAdapter(R.id.recyclerView)
            BaseAdapter<ItemCreateTodoImportanceBinding, ImportanceBean> noticeAdapter = new BaseAdapter<ItemCreateTodoImportanceBinding, ImportanceBean>() {
                @OnClick(R.id.checkBox)
                public void checkBox(ImportanceBean bean) {
                    Log.d(TAG, "checkBox() called with: bean = [" + bean.checked + "]");
                    checkedNotice = bean;
                    for (ImportanceBean noticeBean : list) {
                        noticeBean.checked = false;
                    }
                    bean.checked = true;
                    notifyDataSetChanged();
                    mBinding.noNotice.setChecked(false);
                }
            };

            @OnClick(R.id.close)
            public void quit() {
                dismiss();
            }

            @OnClick(R.id.noNotice)
            public void noNotice() {
                for (ImportanceBean noticeBean : list) {
                    noticeBean.checked = false;
                }
                checkedNotice = null;
                noticeAdapter.notifyDataSetChanged();
            }

            List<ImportanceBean> list = new ArrayList<>();

            //            重复周期类型 1=天 2=周 3=月 4=年
            @Override
            protected void initView() {
                super.initView();
                list.add(new ImportanceBean("高", R.drawable.label_h, 3));
                list.add(new ImportanceBean("中", R.drawable.label_m, 2));
                list.add(new ImportanceBean("低", R.drawable.label_l, 1));
                if (checkedNotice == null) {
                    mBinding.noNotice.setChecked(true);
                } else {
                    for (ImportanceBean cycleBean : list) {
                        if (cycleBean.name.equals(checkedNotice.name)) {
                            cycleBean.checked = true;
                        }
                    }
                }
                noticeAdapter.setData(list);
            }

            @OnClick(R.id.confirm)
            public void confirm() {
//                mNoticeBean = checkedNotice;
                if (checkedNotice != null) {
                    bean.right = checkedNotice.name;
                    actionBean.momentsMatter = checkedNotice.value;
                } else {
                    actionBean.momentsMatter = 0;
                    bean.right = "无";
                }
                midAdapter.notifyDataSetChanged();
                dismiss();
            }

        };
        new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
    }

    DetailBean todoBean = new DetailBean();

    public void save(View view) {
        if (actionBean.startTime == null) {
            ToastUtils.showShort("请设置开始时间");
            return;
        }
        todoBean.contactIds.clear();
        for (ContactBean contactBean : contactBeanList) {
            todoBean.contactIds.add(contactBean.id);
        }
        actionBean.dayTipsStatus = mBinding.toggle.isChecked();
        if (todoBean.id != 0) {
            API.calendarEdit(todoBean).enqueue(new ResultCallback<Boolean>() {
                @Override
                protected void onSuccess(Boolean aBoolean) {
                    finish();
                }
            });
            return;
        }
        API.calendarCreate(todoBean).watch(this, new HttpCallback<Boolean>() {
            @Override
            protected void onSuccess(Boolean aBoolean) {
                finish();
            }
        });
    }

    public static class CycleBean {

        public int cycleType;
        public int cycleTime;
        public String name;
        public boolean checked;

        public CycleBean(String name, int cycleType, int cycleTime) {
            this.cycleType = cycleType;
            this.cycleTime = cycleTime;
            this.name = name;
        }

        public CycleBean(int cycleType, int cycleTime) {
            this.cycleType = cycleType;
            this.cycleTime = cycleTime;
            this.name = CycleUtil.getCycleName(cycleType, cycleTime);
        }
    }

    public static class ImportanceBean {
        public int res;  //        重要时刻 0=无 1=低 2=中 3=高
        public int value;
        public String name;
        public boolean checked;

        public ImportanceBean(String name, int res, int value) {
            this.res = res;
            this.value = value;
            this.name = name;
        }

        public ImportanceBean(int momentsMatter) {
            this.value = momentsMatter;
            if (momentsMatter == 1) {
                this.res = R.drawable.label_l;
                this.name = "低";
            } else if (momentsMatter == 2) {
                this.res = R.drawable.label_m;
                this.name = "中";

            } else if (momentsMatter == 3) {
                this.res = R.drawable.label_h;
                this.name = "高";
            }
        }
    }

    private void showCyclePop(Label2.LabelBean bean) {
        BottomPopup bottomPopup = new BottomPopup<PopTodoCycleBinding>(mActivity) {

            CycleBean checkedNotice = actionBean.cycleTipsStatus ? new CycleBean(actionBean.cycleType, actionBean.cycleTime) : null;
            @BindAdapter(R.id.recyclerView)
            BaseAdapter<ItemCreateTodoCycleBinding, CycleBean> noticeAdapter = new BaseAdapter<ItemCreateTodoCycleBinding, CycleBean>() {
                @OnClick(R.id.checkBox)
                public void checkBox(CycleBean bean) {
                    Log.d(TAG, "checkBox() called with: bean = [" + bean.checked + "]");
                    checkedNotice = bean;
                    for (CycleBean noticeBean : list) {
                        noticeBean.checked = false;
                    }
                    bean.checked = true;
                    notifyDataSetChanged();
                    mBinding.noNotice.setChecked(false);
                }
            };

            @OnClick(R.id.close)
            public void quit() {
                dismiss();
            }

            @OnClick(R.id.noNotice)
            public void noNotice() {
                for (CycleBean noticeBean : list) {
                    noticeBean.checked = false;
                }
                noticeAdapter.notifyDataSetChanged();
                checkedNotice = null;
                mBinding.noNotice.setChecked(true);
            }

            List<CycleBean> list = new ArrayList<>();

            //            重复周期类型 1=天 2=周 3=月 4=年
            @Override
            protected void initView() {
                super.initView();
                list.add(new CycleBean("每天", 1, 1));
                list.add(new CycleBean("每周", 2, 1));
                list.add(new CycleBean("每两周", 2, 2));
                list.add(new CycleBean("每月", 3, 1));
                list.add(new CycleBean("每季度", 3, 4));
                list.add(new CycleBean("每半年", 3, 6));
                list.add(new CycleBean("每年", 4, 1));
                if (checkedNotice == null) {
                    mBinding.noNotice.setChecked(true);
                } else {
                    for (CycleBean cycleBean : list) {
                        if (cycleBean.name.equals(checkedNotice.name)) {
                            cycleBean.checked = true;
                        }
                    }
                }
                noticeAdapter.setData(list);
            }

            @OnClick(R.id.confirm)
            public void confirm() {
                if (checkedNotice != null) {
                    bean.right = checkedNotice.name;
                    actionBean.cycleTipsStatus = true;
                    actionBean.cycleType = checkedNotice.cycleType;
                    actionBean.cycleTime = checkedNotice.cycleTime;
                } else {
                    actionBean.cycleTipsStatus = false;
                    actionBean.cycleType = 0;
                    actionBean.cycleTime = 0;
                    bean.right = "无";
                }
                midAdapter.notifyDataSetChanged();
                dismiss();
            }

        };
        new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
    }

    private void showPopNotice(Label2.LabelBean bean) {
        BottomPopup bottomPopup = new BottomPopup<PopTodoNoticeBinding>(mActivity) {
            NoticeBean checkedNotice = new NoticeBean(actionBean.tipsPreType, actionBean.tipsPreTime);
            @BindAdapter(R.id.recyclerView)
            BaseAdapter<ItemCreateTodoNoticeBinding, NoticeBean> noticeAdapter = new BaseAdapter<ItemCreateTodoNoticeBinding, NoticeBean>() {
                @OnClick(R.id.checkBox)
                public void checkBox(NoticeBean bean) {
                    checkedNotice = bean;
                    for (NoticeBean noticeBean : list) {
                        noticeBean.checked = false;
                    }
                    bean.checked = true;
                    notifyDataSetChanged();
                    mBinding.noNotice.setChecked(false);
                }
            };

            @OnClick(R.id.close)
            public void quit() {
                dismiss();
            }

            @OnClick(R.id.noNotice)
            public void noNotice() {
                for (NoticeBean noticeBean : list) {
                    noticeBean.checked = false;
                }
                noticeAdapter.notifyDataSetChanged();
                checkedNotice = new NoticeBean("不提醒", 0, 0);
                mBinding.noNotice.setChecked(true);
            }

            List<NoticeBean> list = new ArrayList<>();

            @Override
            protected void initView() {
                super.initView();
                list.add(new NoticeBean("准时", 1, 0));
                list.add(new NoticeBean("提前5分钟", 2, 5));
                list.add(new NoticeBean("提前10分钟", 2, 10));
                list.add(new NoticeBean("提前15分钟", 2, 15));
                list.add(new NoticeBean("提前30分钟", 2, 30));
                list.add(new NoticeBean("提前1小时", 3, 1));
                list.add(new NoticeBean("提前2小时", 3, 2));
                list.add(new NoticeBean("提前1天", 4, 1));
                list.add(new NoticeBean("提前2天", 4, 2));
                list.add(new NoticeBean("提前1周", 5, 1));
                boolean flag = false;
                for (NoticeBean noticeBean : list) {
                    if (noticeBean.name.equals(checkedNotice.name)) {
                        noticeBean.checked = true;
                        flag = true;
                        break;
                    }
                }
                noticeAdapter.setData(list);
                mBinding.noNotice.setChecked(!flag);
            }

            @OnClick(R.id.confirm)
            public void confirm() {
                bean.right = checkedNotice.name;
                midAdapter.notifyDataSetChanged();
                actionBean.tipsPreType = checkedNotice.tipsPreType;
                actionBean.tipsPreTime = checkedNotice.tipsPreTime;
                dismiss();
            }

        };
        new XPopup.Builder(mActivity).asCustom(bottomPopup).show();
    }

    @BindAdapter(R.id.recyclerView)
    BaseAdapter<ItemContactEditContactBinding, ContactBean> contactAdapter = new BaseAdapter<ItemContactEditContactBinding, ContactBean>() {
        @Override
        protected void onBindData(ItemContactEditContactBinding binding, ContactBean bean, int position) {
            super.onBindData(binding, bean, position);
            List<Integer> groupIdList = bean.groupIdList;
            binding.avatar.setImageResource(AvatarUtil.getAvatar(bean.gender));
            LinearLayoutManager layoutManager = (LinearLayoutManager) binding.groupRecyclerView.getLayoutManager();
            layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            BaseAdapter<ItemSelectGroupDetailBinding, GroupBean> groupBeanBaseAdapter = new BaseAdapter<ItemSelectGroupDetailBinding, GroupBean>() {
            };
            binding.groupRecyclerView.setAdapter(groupBeanBaseAdapter);
            groupBeanBaseAdapter.setData(bean.relationGroupList);
        }
    };
    List<ContactBean> contactBeanList = new ArrayList<>();
    ActionBean actionBean = new ActionBean();

    @Subscribe(sticky = true)
    public void onMessage(EventBean eventBean) {
        EventBus.getDefault().removeStickyEvent(eventBean);
        API.getCalendarActionDetail(eventBean.id).watch(this, new HttpCallback<DetailBean<ActionBean>>() {

            @Override
            protected void onSuccess(DetailBean<ActionBean> actionBeanDetailBean) {
                if (actionBeanDetailBean == null || actionBeanDetailBean.data == null) {
                    return;
                }
                todoBean = actionBeanDetailBean;
                todoBean.eventType = 4;
                todoBean.contactIds = new ArrayList<>();
                mBinding.setBean(actionBeanDetailBean.data);
                actionBean = actionBeanDetailBean.data;
                if (actionBeanDetailBean.contactInfoList != null) {
                    for (DetailBean.ContactInfoList contactInfoList : actionBeanDetailBean.contactInfoList) {
                        contactBeanList.add(new ContactBean(contactInfoList));
                    }
                }
                if (contactBeanList.isEmpty()) {
                    mBinding.selectPerson.setVisibility(View.VISIBLE);
                    mBinding.recyclerView.setVisibility(GONE);
                    mBinding.addContacts.setVisibility(View.GONE);
                } else {
                    mBinding.recyclerView.setVisibility(VISIBLE);
                    mBinding.selectPerson.setVisibility(View.GONE);
                    mBinding.addContacts.setVisibility(View.VISIBLE);
                }
                contactAdapter.setData(contactBeanList);

                mBinding.toggle.setChecked(actionBean.dayTipsStatus);

                topAdapter.getData().get(0).right = actionBean.getStartTime();
                topAdapter.getData().get(1).right = actionBean.getEndTime();
                topAdapter.notifyDataSetChanged();
//                "tipsPreType":0,"tipsPreTime":0,"cycleTipsStatus":false,"cycleType":0,"cycleTime":0,"momentsMatter":0,"important":false

                midAdapter.getData().get(0).right = actionBean.getNoticeLabel();
                midAdapter.getData().get(1).right = CycleUtil.getCycleName(actionBean.cycleType, actionBean.cycleTime);
                midAdapter.getData().get(2).right = actionBean.getImportance();
                midAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                super.onError(errorCode, errorMessage);
                finish();
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        todoBean.data = actionBean;
        todoBean.eventType = 4;
        todoBean.contactIds = new ArrayList<>();
        mBinding.setBean(actionBean);
        List<Label2.LabelBean> top = new ArrayList<>();
        top.add(new Label2.LabelBean("开始时间", "请选择开始时间", 0, true));
        top.add(new Label2.LabelBean("结束时间", "请选择结束时间", 0, true));
        topAdapter.setData(top);
        List<Label2.LabelBean> mid = new ArrayList<>();
        mid.add(new Label2.LabelBean("提醒", "不提醒", 0, true));
        mid.add(new Label2.LabelBean("重复", "无", 0, true));
        mid.add(new Label2.LabelBean("重要程度", "无", 0, true));
        midAdapter.setData(mid);
        if (contactBeanList.isEmpty()) {
            mBinding.selectPerson.setVisibility(View.VISIBLE);
            mBinding.recyclerView.setVisibility(GONE);
            mBinding.addContacts.setVisibility(View.GONE);
        } else {
            mBinding.recyclerView.setVisibility(VISIBLE);
            mBinding.selectPerson.setVisibility(View.GONE);
            mBinding.addContacts.setVisibility(View.VISIBLE);
        }
    }


    public void goContacts(View view) {
        DataStore.put(SelectPersonActivity.class.getName(), contactBeanList);
        startActivityForResult(SelectPersonActivity.class, new Runnable() {
            @Override
            public void run() {
                List<ContactBean> contactBeans = DataStore.remove(SelectPersonActivity.class.getName());
                if (contactBeans != null) {
                    contactBeanList.clear();
                    contactBeanList.addAll(contactBeans);
                    if (contactBeanList.isEmpty()) {
                        mBinding.selectPerson.setVisibility(View.VISIBLE);
                        mBinding.recyclerView.setVisibility(GONE);
                        mBinding.addContacts.setVisibility(View.GONE);
                    } else {
                        mBinding.recyclerView.setVisibility(VISIBLE);
                        mBinding.selectPerson.setVisibility(View.GONE);
                        mBinding.addContacts.setVisibility(View.VISIBLE);
                    }
                    contactAdapter.setData(contactBeanList);
                }
                Log.i(TAG, "run: " + contactBeanList.size());
            }
        });
    }

    public static class NoticeBean {
        public String name;
        public int tipsPreType;
        public int tipsPreTime;
        public boolean checked;

        public NoticeBean(String name, int tipsPreType, int tipsPreTime) {
            this.name = name;
            this.tipsPreType = tipsPreType;
            this.tipsPreTime = tipsPreTime;
        }

        public NoticeBean(int tipsPreType, int tipsPreTime) {
            this.tipsPreType = tipsPreType;
            this.tipsPreTime = tipsPreTime;
//            "不提醒", 0, 0
//            list.add(new NoticeBean("准时", 1, 0));
//            list.add(new NoticeBean("提前5分钟", 2, 5));
//            list.add(new NoticeBean("提前10分钟", 2, 10));
//            list.add(new NoticeBean("提前15分钟", 2, 15));
//            list.add(new NoticeBean("提前30分钟", 2, 30));
//            list.add(new NoticeBean("提前1小时", 3, 1));
//            list.add(new NoticeBean("提前2小时", 3, 2));
//            list.add(new NoticeBean("提前1天", 4, 1));
//            list.add(new NoticeBean("提前2天", 4, 2));
//            list.add(new NoticeBean("提前1周", 5, 1));
            name = NoticeUtil.getNoticeLabel(tipsPreType, tipsPreTime);
        }
    }
}